let userlistModule = (() => {
  let
    userdepartment = $('.selectBox'),
    searchInp = $('.searchInp'),
    tbody = $('.tableBox').find('tbody'),
    deleteAll = $('.deleteAll'),
    checkAll = $('#checkAll'),
    checkList = null;


  // 渲染department
  let get_options = async function () {
    // 获取department
    let
      departmentData = await queryDepartment(),
      str = '';
    if (!departmentData.code) {
      str += `<option value="0">全部</option>`
      departmentData.data.forEach(item => {
        str += `<option value="${item.id}">${item.name}</option>`
      })
      userdepartment.html(str)
    }
  }
  // 渲染user
  let render_user = async function () {
    let
      params = {
        departmentId: userdepartment.val(),
        search: searchInp.val().trim()
      },
      res = await axios.get('/user/list', { params })
    if (!res.code) {
      let
        str = ``;
      res.data.forEach(item => {
        str += `			
        <tr>
          <td class="w3"><input type="checkbox" userId="${item.id}"></td>
          <td class="w10">${item.name}</td>
          <td class="w5">${item.sex == 0 ? '男' : '女'}</td>
          <td class="w10">${item.department}</td>
          <td class="w10">${item.job}</td>
          <td class="w15">${item.email}</td>
          <td class="w15">${item.phone}</td>
          <td class="w20">${item.desc}</td>
          <td class="w12" userId="${item.id}">
            <a href="javascript:;">编辑</a>
            <a href="javascript:;">删除</a>
            <a href="javascript:;">重置密码</a>
          </td>
        </tr> 
        `
      })
      tbody.html(str)
      checkList = tbody.find('input[type="checkbox"]')
    }
  }
  // search事件绑定
  let bindSearch = () => {
    userdepartment.change(render_user);
    searchInp.on('keydown', ev => {
      if (ev.keyCode === 13) {
        render_user()
      }
    })
  }
  // 批量删除按钮button的删除绑定，全选和部分选的绑定
  let handleDeleteAll = () => {
    // 全选按钮事件绑定
    checkAll.click(ev => {
      let checkFlag = checkAll.prop('checked');
      checkList.prop('checked', checkFlag)
    })

    // 单按钮绑定，事件委托
    tbody.click(ev => {
      let
        target = $(ev.target),
        userId = target.attr('userId'),
        checkFlag = true;
      [].forEach.call(checkList, item => {
        if (!$(item).prop('checked')) {
          checkFlag = false
          return;
        }
      })
      checkAll.prop('checked', checkFlag)
    })

    // 批量删除绑定
    deleteAll.click(ev => {
      let
        flag = confirm(`确定要删除这些用户的信息吗？`),
        arr = [],
        index = -1;
      if (!flag) return;

      // 获取要删除的userId集合
      [].forEach.call(checkList, item => {
        if ($(item).prop('checked')) {
          arr.push($(item).attr('userId'))
        }
      })
      // 递归删除
      let remove = async function remove() {
        if (index == arr.length - 1) {
          render_user()
          alert('删除成功')
          return;
        };
        let
          userId = arr[++index],
          res = await axios.get('/user/delete', { params: { userId } })
        if (res.code) {
          alert(`删除${userId}的用户操作失败`);
          return;
        }
        remove();
      };
      remove();
    })
  }
  // delegate事件委托绑定
  let bindDelegate = () => {
    tbody.click(async ev => {
      let
        TAG = ev.target.tagName,
        content = ev.target.innerHTML.trim(),
        userId = $(ev.target.parentElement).attr('userId');
      if (TAG === 'A') {
        if (content === '编辑') {
          window.location.href = `useradd.html?userId=${userId}`
        }
        if (content === '删除') {
          let flag = confirm(`确定要删除id为${userId}的用户的信息吗？`)
          if (!flag) return;
          let params = { userId },
            res = await axios.get('/user/delete', { params });
          if (!res.code) {
            alert('删除用户成功');
            $(ev.target).parent().parent().remove();
            checkList = tbody.find('input[type="checkbox"]')
            return
          }
          alert('删除失败')
        }
        if (content === '重置密码') {
          let flag = confirm(`确定要重置id为${userId}的用户的密码吗？`)
          if (!flag) return;
          let res = await axios.post('/user/resetpassword', { userId });
          if (!res.code) {
            alert('重置成功');
            return
          }
          alert('重置失败')
        }
      }
    })
  }
  return {
    init() {
      get_options();
      render_user();
      bindSearch();
      bindDelegate();
      handleDeleteAll();
    }
  }
})()

userlistModule.init()